package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
//让AuthProperties上的@ConfigurationProperties生效
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter {

    @Autowired
    private AuthProperties authProperties;

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //2.获取请求路径
        String path = request.getURI().getPath();
        //配置多个地址
        boolean bo = authProperties.getExcludePaths()
                .stream()
                .anyMatch(url -> antPathMatcher.match(url, path));
        if (bo){
            //3、判断路径是否不需要对令牌进行校验，如果不需要，直接放行（/users/Login）
            return chain.filter(exchange);
        }
        //4、需要拦截校验，获取请求头中的令牌
        String token = request.getHeaders().getFirst("authorization");

        //5、对令牌进行校验
        Long userId =null;
        try {
            jwtTool.parseToken(token);
        } catch (Exception e) {
            //6、校验并不通过，执行拦截操作
            //消息类型 application/json;charset=utf-8
            //响应状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应JSON类型
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }

        //7.TODD 解析令牌，获取用户ID，把用户ID放到请求头中
        String userInfo = userId.toString();
        request.mutate().headers(httpHeaders -> httpHeaders.set("user-info",userInfo));

        //8.放行-->Http请求
        return chain.filter(exchange);
    }
}
